<?php
namespace Api\Controller;
vendor('Firebase.JWT.JWT');

class ReplyController extends BaseController {
    public function replyQuestion() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_auto_data($_REQUEST);
        $studentid = $data['studentid'];
        $student_name = $data['student_name'];
        $teacher_name = $data['teacher_name'];
        $cate_name = $data['cate_name'];
        //1.必填参数判断
        $qid = $data['qid'];
        $rdesc = $data['rdesc'];
        if (!$qid) {
            fail_name('qid');
        }
        $rimgs = $data['rimgs'] ? $data['rimgs'] : '';
        $record = $data['record'] ? htmlspecialchars_decode($data['record']) : '';
        if (!$rdesc && !$rimgs && !$record) {
            fail('请您至少输入问题描述、图片、语音中的其中一项');
        }
        //2.插入数据库
        $money = 1; //回复一个问题得到的金钱数
        M()->startTrans();
        $current_time = time();
        $res = M('qreply')->add(array(
            'qid'         => $qid,
            'uid'         => $uid,
            'rdesc'       => $rdesc,
            'rimgs'       => $rimgs,
            'record'      => $record,
            'get_money'   => $money,
            'create_time' => $current_time,
            'update_time' => $current_time
        ));
        //3、修改提问表的process_state为2
        $q_modify_res = M('question')->where(array(
            'qid' => $qid
        ))->save(array(
            'process_state' => 2
        ));
        //4、添加提问的处理记录，添加前要判断是否已经回答了，因为有多端登录的情况
        $m_qdeal_history = M('qdeal_history');
        $deal_exist = $m_qdeal_history->where(array(
            'qid'           => $qid,
            'uid'           => $uid,
            'process_state' => 2,
        ))->count();
        if ($deal_exist > 0) {
            //如果已经处理过就回滚
            M()->rollback();
            fail('请勿重复回复');
        }
        $qhistory_save_res = $m_qdeal_history->where(array(
            'qid' => $qid,
            'uid' => $uid,
        ))->save(array(
            'process_state' => 2,
            'answer_time'   => $current_time,
            'update_time'   => $current_time
        ));
        //5、教师收入
        $incom_add_res = M('teacher')->where(array(
            'uid' => $uid
        ))->save(array(
            'income'      => array('exp', 'income+' . $money),
            'update_time' => $current_time
        ));
        if (!$res || !$qhistory_save_res || !$q_modify_res || !$incom_add_res) {
            M()->rollback();
            fail('回复失败，请重试');
        } else {
            M()->commit();
            if (!$studentid) {
                succeed(null, '回复成功');
            }
            //计算发送类型
            $q_type = '文字';
            $message = '教师回复提问';
            if ($rdesc) {
                $message = mb_substr($rdesc, 0, (mb_strlen($rdesc, 'utf8') > 50 ? 50 : strlen($rdesc))) . '...';
            }
            if ($rdesc && $rimgs && $record) {
                $q_type = '文字+图片+语音';
            } else if ($rdesc && $rimgs) {
                $q_type = '文字+图片';
            } else if ($rdesc && $record) {
                $q_type = '文字+语音';
            } else if ($rdesc) {
                $q_type = '文字';
            } else if ($rimgs) {
                $q_type = '图片';
                $message = '图片';
            } else if ($record) {
                $q_type = '语音';
                $message = '语音';
            }
            //发送模板消息给学生端
            $m_wxformid = M('wxformid');
            $formidList = $m_wxformid->where(array(
                'uid'       => $studentid,
                'use_state' => 0,
                'expire'    => array('gt', time()),
            ))->limit(0, 1)->order("expire asc")->select();
            if ($formidList) {
                $formBean = $formidList[0];
                $data = array(
                    "keyword1" => array( //回复人
                                         "value" => $teacher_name,
                                         "color" => "#232426"
                    ),
                    "keyword2" => array( //回复内容
                                         "value" => $message,
                                         "color" => "#232426"
                    ),
                    "keyword3" => array( //提问人
                                         "value" => $student_name,
                                         "color" => "#232426"
                    ),
                    "keyword4" => array( //提问类型
                                         "value" => $cate_name,
                                         "color" => "#232426"
                    ),
                    "keyword5" => array( //答案来自
                                         "value" => '水滴作业辅导',
                                         "color" => "#f00"
                    ),
                    "keyword6" => array( //回复时间
                                         "value" => date('Y年m月d日H点i分s秒', $current_time),
                                         "color" => "#f00"
                    ),
                );
                $template_id = C('WX_QUESTION_REPLY');
                $res = sendWXMessage($template_id, $data, $formBean['formid'], $formBean['openid']);
                //置为废弃
                $m_wxformid->where(array(
                    'id' => $formBean['id']
                ))->save(array(
                    'use_state'   => 1,
                    'update_time' => $current_time
                ));
                $m_wxformid->where(array(
                    'use_state' => 1,
                    'expire'    => array('lt', time()),
                    '_logic'    => 'or'
                ))->delete();
            }
            succeed(null, '回复成功' . json_encode($data));
        }
    }

    public function uploadImage() {
        $uploadRes = uploadFile($_FILES['img'], 3 * 1024 * 1024, array(
            'jpg',
            'gif',
            'png',
            'jpeg'
        ), 'Public/upload/image/reply/');
        if ($uploadRes['uploadstatus'] == 200) {
            succeed($uploadRes, '上传成功');
        } else {
            fail($uploadRes['msg']);
        }
    }

    public function uploadRecordFile() {
        $uploadRes = uploadFile($_FILES['record'], 2 * 1024 * 1024, array(
            'mp3',
            'amr'
        ), 'Public/upload/record/reply/', false);
        if ($uploadRes['uploadstatus'] == 200) {
            //利用ffmpeg将arm转换成MP3
            if (getExt($uploadRes['path']) == '.amr') {
                $rootpath = 'C:/phpStudy/PHPTutorial/WWW/shuidiFuDao/';
                $newFile = getPathWithoutExt($uploadRes['path']) . '.mp3';
                $cmd = 'C:/ffmpeg/bin/ffmpeg -i  ' . $rootpath . $uploadRes['path'] . '  ' . $rootpath . $newFile;
                shell_exec($cmd);
                //删除amr文件
                unlink($rootpath . $uploadRes['path']);
                $uploadRes['path'] = $newFile;
            }
            succeed($uploadRes, '上传成功');
        } else {
            fail($uploadRes['msg']);
        }
    }

    //查询回复的详情
    public function getQuestionReplyDetail() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_auto_data($_REQUEST);
        $qid = $data['qid'];
        if (!$qid) {
            fail_name('qid');
        }
        $reply_data = M()->query("select r.uid,r.rdesc,r.rimgs,r.record,r.create_time,t.nick_name,t.head_img
                  from t_qreply  as r,t_teacher as t
                  WHERE r.qid={$qid}
                  AND r.uid=t.uid
                  ORDER BY create_time desc 
                  limit 0,1;");
        succeed(get_auto_data($reply_data[0], true), '获取回复详情数据成功');
    }
}